// 配置axios

import axios from "axios";
import { MessageBox, Message, Loading } from "element-ui";
//引入storage方法
import storage from "@/utils/storage";
// import { config } from 'vue/types/umd'

let http = axios.create({
  baseURL: "api",
  timeout: 5000, //超时配置
  withCredentials: true, //携带本地凭据 比如cookie
});

//全局的请求拦截器
let fullScreenLoading = null;
http.interceptors.request.use((config) => {
  //config就是所有的请求配置
  //先获取本地的token,然后携带给后端
  //这里必须用自己封装的storage方法,不能直接用localstorage因为我们需要的是不带引号的,直接写的会带引号 出现问题
  let token = storage.get("qf-token");
  // console.log(token);
  config.headers["authorization"] = token;
  //打开loading动画
  if (
    config.url.indexOf("Login") !== -1 ||
    config.url.indexOf("wechatLogin") !== -1
  ) {
    fullScreenLoading = Loading.service({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }
  // console.log("config", config);
  return config; //放行 不return 那么不能将请求真正的发送出去
});

//全局响应拦截
http.interceptors.response.use((config) => {
  if (fullScreenLoading) {
    fullScreenLoading.close();
    fullScreenLoading = null;
  }
  // console.log(config);
  let { state, msg } = config.data;
  if (!state) {
    MessageBox({
      message: msg,
      title: "错误提示",
      type: "error",
    });
  }
  //10022 1004 这两个状态码分别对应了token过期和session过期
  //10026 没有权限
  //清掉本地缓存,清掉token
  let { code } = config.data;
  if (code === "10022" || code === "1004") {
    Message.error("登入过期,请重新登入");
    storage.rm("qf-token");
    location.reload();
  }
  return config; //如果不retrun axios请求就拿不到任何响应结果
});

export default http;
